const WebSocket = require('ws');
const http = require('http');

const server = http.createServer();
const wss = new WebSocket.Server({ server });

let clientCount = 0;

console.log('🚀 WebRTC信令服务器启动中...');
console.log('==========================================');

wss.on('connection', (ws) => {
    const clientId = `Client_${++clientCount}_${Math.random().toString(36).substring(2, 8)}`;
    console.log(`✅ 新客户端连接: ${clientId}`);
    console.log(`📊 当前连接数: ${wss.clients.size}`);
    
    // 发送欢迎消息
    ws.send(JSON.stringify({
        type: 'welcome',
        clientId: clientId,
        clientCount: wss.clients.size,
        timestamp: new Date().toISOString()
    }));

    // 广播新用户加入
    broadcast({
        type: 'user-joined',
        clientId: clientId,
        clientCount: wss.clients.size,
        timestamp: new Date().toISOString()
    }, clientId);

    ws.on('message', (message) => {
        try {
            const data = JSON.parse(message.toString());
            const logType = getMessageType(data.type);
            console.log(`📨 ${logType} ${clientId} -> ${data.type}`);
            
            // 广播给所有其他客户端
            broadcast(data, clientId);
        } catch (error) {
            console.error('❌ 解析消息失败:', error);
        }
    });
    
    ws.on('close', (code, reason) => {
        console.log(`❌ 客户端断开: ${clientId} (代码: ${code})`);
        console.log(`📊 当前连接数: ${wss.clients.size}`);
        
        // 广播用户离开
        broadcast({
            type: 'user-left',
            clientId: clientId,
            clientCount: wss.clients.size,
            timestamp: new Date().toISOString()
        });
    });

    ws.on('error', (error) => {
        console.log(`⚠️ 客户端错误 ${clientId}:`, error.message);
    });
});

function broadcast(message, excludeClientId = null) {
    const messageStr = JSON.stringify(message);
    wss.clients.forEach((client, clientId) => {
        if (clientId !== excludeClientId && client.readyState === WebSocket.OPEN) {
            client.send(messageStr);
        }
    });
}

function getMessageType(type) {
    const types = {
        'offer': '📤',
        'answer': '📥',
        'ice-candidate': '🧊',
        'welcome': '👋',
        'user-joined': '🆕',
        'user-left': '👋'
    };
    return types[type] || '📝';
}

const PORT = 8080;
server.listen(PORT, '0.0.0.0', () => {
    console.log(`✅ 信令服务器运行在: ws://0.0.0.0:${PORT}`);
    console.log(`📱 网页访问地址: http://你的IP:8081/index.html`);
    console.log('==========================================\n');
});

// 优雅关闭
process.on('SIGINT', () => {
    console.log('\n🛑 收到关闭信号，正在关闭信令服务器...');
    wss.clients.forEach(client => {
        client.close(1000, 'Server shutdown');
    });
    wss.close(() => {
        console.log('✅ 信令服务器已安全关闭');
        process.exit(0);
    });
});